<template>
  <div class="about">
    <a-card style="width: 100%; height:100%">
      <div slot="title">
        <a-button type="primary" @click="showRoleModal">创建角色</a-button>&nbsp;&nbsp;&nbsp;
        <a-button type="primary" :disabled="!hasSelected" @click="showAuthModal">设置角色权限</a-button>
      </div>
      <a-table
        :loading="loading"
        :rowSelection="{type: 'radio',selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
        :columns="columns"
        :dataSource="roleList"
        :pagination="{defaultPageSize: 5}"
      />
    </a-card>
    <div>
      <a-modal
        title="添加角色"
        :visible="roleVisible"
        @ok="handRoleleOk"
        :confirmLoading="confirmLoading"
        @cancel="handleCancel"
      >
        <add-role-form @initForm="iniRoleForm" />
      </a-modal>
      <a-modal
        title="授权"
        :visible="authVisible"
        @ok="handAuthOk"
        :confirmLoading="authConfirmLoading"
        @cancel="handleCancel"
      >
        <!-- <add-role-form @initForm="iniRoleForm"/> -->
        <a-form :form="roleForm">
          <a-form-item label="角色名称" :label-col="{ span: 5 }" :wrapper-col="{ span: 12 }">
            <!-- <a-input v-decorator="['roleName', { rules: [{ required: true, message: '角色名称必须输入!' }] }]" /> -->
            <a-input v-model="selectedRole.name" disabled />
          </a-form-item>
          <a-form-item label="权限选择" :label-col="{ span: 5 }" :wrapper-col="{ span: 12 }">
            <a-tree
              checkable
              :defaultExpandAll="true"
              v-model="checkedKeys"
              :treeData="authMenu"
            />
            
          </a-form-item>
        </a-form>
      </a-modal>
    </div>
  </div>
</template>
<script>
const columns = [
  {
    title: "角色名称",
    dataIndex: "name"
  },
  {
    title: "创建时间",
    dataIndex: "create_time"
  },
  {
    title: "授权时间",
    dataIndex: "auth_time"
  },
  {
    title: "授权人",
    dataIndex: "auth_name"
  }
];


import authMenu from "../../config/authList";
import addRoleForm from "./addRoleForm/addRoleForm";
import { reqRoles, reqAddRole, reqUpdateRole } from "../../api/index";
import { message } from "ant-design-vue";
import dateUtils from "../../utils/dateUtils";
import storageUtil from '../../utils/storageUtil'
export default {
  created() {
    this.reqRoles();
  },
  data() {
    return {
      autoExpandParent: true,
      checkedKeys: [],  //选中的权限数组
      authMenu, //权限树的菜单
      selectedRole: {}, // 被选中的角色
      roleForm: this.$form.createForm(this, { name: "roleForm" }),
      loading: false,
      roleList: [],
      columns,
      selectedRowKeys: [], // Check here to configure the default column
      loading: false,
      roleVisible: false, //角色模态框显隐藏
      authVisible: false,
      confirmLoading: false, //角色表单的确认按钮是否加载状态
      authConfirmLoading: false //授权表单的确认按钮是否加载状态
    };
  },
  watch: {
    checkedKeys(val) {
      console.log("onCheck", val);
      this.checkedKeys = val
    }
  },
  components: {
    "add-role-form": addRoleForm
  },
  computed: {
    //是否有表格行被选中
    hasSelected() {
      return this.selectedRowKeys.length > 0;
    }
  },
  methods: {
    //更新选中的权限
    onCheck(checkedKeys) {
      console.log("onCheck", checkedKeys);
      this.checkedKeys = checkedKeys;
    },
    //接受roleForm组件发送过来的roleForm对象
    iniRoleForm(roleform) {
      this.roleForm = roleform;
    },
    //显示权限模态框
    showAuthModal() {
      this.checkedKeys = this.selectedRole.value.menus
      this.authVisible = true;
    },
    //显示添加角色模态框
    showRoleModal() {
      this.roleVisible = true;
    },
    //授权模态框中的确认按钮
    async handAuthOk() {
      var auth_time = Date.now()
      var {__v, _id, create_time, name} = this.selectedRole.value
      var auth_name = storageUtil.getUser().username
      var role = {__v, _id, auth_name, create_time, name, auth_time, menus:this.checkedKeys} 
     var result = await reqUpdateRole(role)
     if(result.status == 0){
      this.authVisible = false;
      // console.log(result)
      this.reqRoles()
     }else{
       message.error("授权失败!")
     }
    },
    //添加模态框中的确认按钮
    handRoleleOk(e) {
      this.roleForm.validateFields(async (err, values) => {
        if (!err) {
          this.confirmLoading = true;
          var roleName = values.roleName;
          const result = await reqAddRole(roleName);
          if (result.status == 0) {
            var data = result.data;
            data.key = data._id;
            data.create_time = dateUtils.formate_Date(data.create_time);
            this.roleList.push(data);
          }
          this.roleForm.resetFields(["roleName"]);
          this.roleVisible = false;
          this.confirmLoading = false;
        }
      });
    },
    handleCancel(e) {
      this.roleForm.resetFields(["roleName"]);
      this.roleVisible = false;
      this.authVisible = false;
    },
    //获取角色列表
    async reqRoles() {
      this.loading = true;
      var result = await reqRoles();
      var data = result.data;
      if (result.status == 0) {
        data.forEach(element => {
          var value = JSON.parse(JSON.stringify(element))
          element.key = element._id;
          element.create_time = dateUtils.formate_Date(element.create_time);
          element.auth_time = dateUtils.formate_Date(element.auth_time);
          element.value = value
        });
        this.roleList = data;
      } else {
        message.error("获取角色列表加载失败!");
      }
      this.loading = false;
    },
    //表格（行）选中变化是触发
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRole = selectedRowKeys;
      this.selectedRole = selectedRows[0];
      this.selectedRowKeys = selectedRowKeys;
    }
  }
};
</script>
